#include <iostream>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include "Mutex.hpp"

#define NUM 4

using namespace LockModule;

int ticketnum = 10000;
Mutex mutex;

void* GetTicket(void* args)
{
    char* name = static_cast<char*>(args);
    while (1)
    {
        {
            LockGuard LockGuard(mutex);
            if (ticketnum > 0)
            {
                usleep(1000);
                printf("%s[%ld] get a ticket: %d\n", name, pthread_self(), ticketnum--);
                usleep(50);
            }
            else break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t tid1, tid2, tid3, tid4;
    pthread_create(&tid1, nullptr, GetTicket, (void*)"thread-1");
    pthread_create(&tid2, nullptr, GetTicket, (void*)"thread-2");
    pthread_create(&tid3, nullptr, GetTicket, (void*)"thread-3");
    pthread_create(&tid4, nullptr, GetTicket, (void*)"thread-4");

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
    return 0;
}